import { exec } from "child_process";
import { dirname } from "path";
import { fileURLToPath } from "url";
import { promisify } from "util";

const execAsync = promisify(exec); // 将 exec 转换为返回 Promise 的函数

/**
 *
 * @param {*} cmd 执行命令
 * @param {*} cwd  工作目录
 */
export async function runCommand(cmd, cwd) {
  console.log(`执行命令: ${cmd}`);
  console.log(`工作目录: ${cwd}`);
  try {
    const stdout = await execAsync(cmd, {
      cwd,
      encoding: "utf-8",
      stdio: ["ignore", "pipe", "pipe"],
    });
    // 返回 audit 的 JSON 结果
    return stdout.stdout.toString();
  } catch (error) {
    // 但返回了错误码（因为发现了漏洞）
    console.error('命令执行出错:');
    if (error.stdout) {
      return error.stdout.toString();
    }
  }
}

export function uniqueId() {
  return Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
}

export function getFilename(importMetaUrl) {
  // 将import.meta.url转成绝对路径,相当于__filename
  return fileURLToPath(importMetaUrl);
}

export function getDirname(importMetaUrl) {
  //  将import.meta.url转成绝对路径,后，转成目录路径
  return dirname(getFilename(importMetaUrl));
}


export function getTime() {
  const now = new Date();
  
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours} ${minutes} ${seconds}`;
}